package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.bean.Setmeal;
import com.itheima.bean.SetmealDish;
import com.itheima.dao.SetmealDao;
import com.itheima.dao.SetmealDishDao;
import com.itheima.dto.SetmealDto;
import com.itheima.exception.CustomException;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealDao, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishDao setmealDishDao;

    @Override
    public void saveWithDishes(SetmealDto setmealDto) {
        //1.判断套餐名称是否存在
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Setmeal::getName,setmealDto.getName());
        int count = this.count(wrapper);
        if(count>0){
            throw new CustomException("套餐名称【"+setmealDto.getName()+"】已经存在！");
        }

        //2.保存套餐基本信息到套餐表setmeal中
        this.save(setmealDto);

        //3.保存套餐包含的菜品信息到套餐菜品表setmeal_dish中
        // 3.1:获取套餐id
        Long setmealId = setmealDto.getId();

        // 3.2：设置每个菜品所属的套餐id 保存到setmeal_dish表中
        setmealDto.getSetmealDishes().forEach(setmealDish -> {
            setmealDish.setSetmealId(setmealId);
            setmealDishDao.insert(setmealDish);
        });

    }

    @Override
    public void deleteWithDishes(Long[] ids) {
        //0.判断是否有传递要删除的套餐id
        if(ids==null || ids.length==0){
            throw new CustomException("要删除的套餐id不能为空！");
        }

        //1.判断要删除的套餐是否处于停售状态
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Setmeal::getId,ids);         //where id in (1,2)
        wrapper.eq(Setmeal::getStatus,1);   //where status = 1  启售的
        List<Setmeal> list = this.list(wrapper);
        if (list!=null && list.size()>0){
            for (Setmeal setmeal : list) {
                throw new CustomException("套餐【"+setmeal.getName()+"】处于启售状态！");
            }
        }

        //2.根据id去套餐表setmeal中删除套餐    Arrays.asList(ids)：将数组转为list集合
        this.removeByIds(Arrays.asList(ids));

        //3.根据id去套餐菜品表setmeal_dish中删除当前套餐下包含的菜品信息
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId,ids); //where setmealId in (1,2)
        setmealDishDao.delete(setmealDishLambdaQueryWrapper);
    }
}
